const charset = require('superagent-charset');
const superagent =  charset(require('superagent'));
require('superagent-proxy')(superagent);

const {
    wxpusher,
    ua, chUa,
    platform,
    pricingCookie,
} = require('./ti_scan_config');

const {
    readTask,
} = require('./ti_logic_read_task');

const {
    logger,
    sleep,
    httpGet,
    httpPost,
} = require('./util');

process.on('unhandledRejection', error => {
    //...不处理...
});

const httpDigiGet = (url, domain, referer) => {
    let language;
    let currency;
    if (domain.indexOf('digikey.sg') > -1) {
        language = 'en-sg';
        currency = 'SGD';
    } else if (domain.indexOf('digikey.cn') > -1) {
        language = 'zh-cn';
        currency = 'CNY';
    } else {
        language = 'en-us';
        currency = 'USD';
    }

	return new Promise((resolve, reject) => {
		superagent.get(url).timeout(20000)
			.set('User-Agent',ua)
			.set('Referer', referer)
            .set('accept-language', language)
            .set('x-currency', currency)
            .set('Cookie', pricingCookie)
            .set('sec-ch-ua', chUa)
            .set('sec-ch-ua-mobile', '?0')
            .set('sec-ch-ua-platform', '"'+platform+'"')
            .set('sec-fetch-dest', 'empty')
            .set('sec-fetch-mode', 'cors')
            .set('sec-fetch-site', 'same-origin')
            .set('accept', '*/*')
            .set('accept-encoding', 'gzip, deflate, br')
			.end((err, res) => {
				if (err) {
					return reject(err);
				}
				resolve(res.text);
			});
	});
}

const serialMap = {};//已启动到任务

//每N秒重新拉取任务列表
(async () => {
    const url = 'https://bomcross.ti.com/distributorSearch/XXXXX?qty=1000';

    while (1) {
        const tasks = await readTask();
        if (!tasks) {
            await sleep(5000);
            continue;
        }

        const taskSerials = [];
        let counter = 0;
        //启动任务
        for (const task of tasks) {
            if (task.status != 1) continue;

            //读取digi-key的id值
            let id;
            let domain;
            let lang;
            try {
                const fullUrl = url.replace('XXXXX', encodeURIComponent(task.serial));
                const str = await httpGet(fullUrl, 'https://bomcross.ti.com/');
                const ret = JSON.parse(str);
                const tmp = ret.html.match(/https:\/\/www.digikey.([^\?]+)/);
                const tmp1 = tmp[0].split('/');
                domain = tmp1[2];
                lang = tmp1[4];
                const tmp2 = tmp[1].split('/');
                id = tmp2[tmp2.length - 1];
                logger('task', id, domain, lang);
            } catch(e) {
                logger('读取id出错', e);
                continue;
            }

            taskSerials.push(task.serial);
            if (!serialMap[task.serial]) {
                serialMap[task.serial] = 1;

                (async (serial, id, domain, lang, counter) => {
                    if (counter % 10 > 0) {
                        await sleep(counter % 10 * 1000);
                    }
                    logger(counter, serial, id, '启动');

                    while (1) {
                        if (!serialMap[serial]) {
                            logger(serial, '关闭');
                            return;
                        }
                        
                        const fullUrl = 'https://'+domain+'/products/api/v4/pricing/'+id;
                        const refer = 'https://'+domain+'/'+lang+'/products/detail/texas-instruments/'+encodeURIComponent(serial)+'/'+id+'?utm_campaign=buynow&utm_medium=aggregator&WT.z_cid=ref_findchips_standard&utm_source=findchips';
                        try {
                            const str = await httpDigiGet(fullUrl, domain, refer);
                            const ret = JSON.parse(str);
                            for (const v of ret.data.messages) {
                                if (v.type == 'qtyAvailableNotes') {
                                    //logger(serial, v.message);
                                    if (v.message.indexOf('Factory Stock') > -1 || v.message.indexOf('厂方库存') > -1) {
                                        logger(serial, v.message);
                                    }
                                    if (v.code == '4') {
                                        const stock = v.message;
                                        const msg = `规格 ${serial} 发现有 ${stock} 库存可以下单`;
                                        logger(msg);
    
                                        try {
                                            //推送消息
                                            await httpPost('http://wxpusher.zjiecode.com/api/send/message', JSON.stringify({
                                                appToken: wxpusher.appToken,
                                                content: msg,
                                                contentType: 1,
                                                uids: wxpusher.uids,
                                            }), 'application/json');
                                        } catch(e) {
                                            logger(e);
                                        }
                                        await sleep(60000);
                                    }
                                }
                            }
                        } catch(e) {
                            logger('请求出错', e);
                            await sleep(5000);
                            continue;
                        }

                        await sleep(2000);
                    }
                })(task.serial, id, domain, lang, counter++);
            }
        }

        //关闭任务
        for (const serial in serialMap) {
            if (taskSerials.indexOf(serial) < 0) {
                delete serialMap[serial];
            }
        }

        await sleep(30000);
    }
})();
